#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

void error_exit(const char* func)
{
	printf("%s:%m\n",func);
	exit(EXIT_FAILURE);
}

void* run(void* arg)
{
 	int cli_fd = *(int*)arg;
 	char buf[4096];
 	for(;;)
 	{
  		int ret = recv(cli_fd,buf,sizeof(buf),0);
  		if(0 >= ret)
  		{
   			exit(EXIT_SUCCESS);
  		}
  		printf("%s\n",buf);
		printf(">>>");
		fflush(stdout);
 	}
}

int main(int argc,const char* argv[])
{
	// 创建socket对象
	int cli_fd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > cli_fd)
		error_exit("socket");

	// 准备server的通信地址
	struct sockaddr_in addr = {};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(2201);
	addr.sin_addr.s_addr = inet_addr("39.101.75.154");
	socklen_t addrlen = sizeof(addr);

	// 连接server
	if(connect(cli_fd,(struct sockaddr*)&addr,addrlen))
		error_exit("connect");

	char name[20];
	printf("请输入昵称：");
	scanf("%s",name);
	size_t wet = send(cli_fd,name,strlen(name)+1,0);

	pthread_t tid;
 	pthread_create(&tid,NULL,run,&cli_fd);
	
	char buf[4096];
	for(;;)
	{
		printf(">>>");
		scanf("%s",buf);

		// 发送数据
		size_t ret = send(cli_fd,buf,strlen(buf)+1,0);
		if(0 > ret || 0 == strcmp("quit",buf))
			break;
	}

	printf("退出成功!\n");
	// 关闭socket对象
	close(cli_fd);
	return EXIT_SUCCESS;
}
